package com.chinatechstar.component.commons.support;

import io.jsonwebtoken.lang.Assert;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * 获取Spring容器管理的Bean对象，应用中配置参数
 *
 * @author Rei
 */
@Component
public class ApplicationSupport implements DisposableBean, ApplicationContextAware {

    private static ApplicationContext applicationContext;

    /**
     * 获取配置文件参数值
     *
     * @param paramKey key
     * @return String
     */
    public static String getParamVal(String paramKey) {
        return applicationContext.getEnvironment().getProperty(paramKey);
    }

    /**
     * 获取bean对象
     *
     * @param name 名称
     * @return Object
     */
    public static Object getBean(String name) {
        Assert.hasText(name);
        return applicationContext.getBean(name);
    }

    public static <T> T getBean(Class<T> clazz) {
        return applicationContext.getBean(clazz);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ApplicationSupport.applicationContext = applicationContext;
    }

    /**
     * 获取applicationContext
     *
     * @return ApplicationContext
     */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    @Override
    public void destroy() {
        applicationContext = null;
    }

}
